<template>
    <div>
        <Teleport to="#before-navigation" v-if="targetExists">
            <div class="event-keywords-card card-box">
                <h5 class="card-title">
                    <el-icon size="20" color="#F06423"><Discount /></el-icon>
                    事件關鍵字
                </h5>
                <div class="card-text">
                    <div class="event-item" v-for="(item, index) in eventKey" :key="index">
                        <span class="show-btn" :style="{ backgroundColor: item.color }" @click="eventKeyHandle(item)">
                            <el-icon size="16" color="#fff" v-if="item.isShow"><View /></el-icon>
                            <el-icon size="16" color="#fff" v-else><Hide /></el-icon>
                        </span>
                        <span class="icon">
                            <el-icon size="16" :color="item.color"><component :is="item.icon" /></el-icon>
                        </span>
                        <span class="event-text">{{ item.isShow ? '隱藏' : '显示' }} {{ item.text }} 事件</span>
                    </div>
                </div>
            </div>
            <div class="calendar-list-card card-box">
                <h5 class="card-title">
                    <el-icon size="20" color="#F06423"><Discount /></el-icon>
                    逐月檢視
                </h5>
                <div class="card-text">
                    <div class="computed-hide">{{ prevMonthComputed }}{{ nextMonthComputed }}</div>
                    <el-calendar v-model="prevMonthDate" @update:model-value="onDateChange('prev')">
                        <template #header="{ date }">{{ date }}</template>
                        <template #date-cell="{ data }">
                            <div :class="{ 'is-selected': eventsList.some(e => e.date === data.day) }">{{ moment(data.date).format('DD') }}</div>
                        </template>
                    </el-calendar>
                    <el-calendar v-model="currentMonthDate" @update:model-value="onDateChange('current')">
                        <template #header="{ date }">{{ date }}</template>
                        <template #date-cell="{ data }">
                            <div :class="{ 'is-selected': eventsList.some(e => e.date === data.day) }">{{ moment(data.date).format('DD') }}</div>
                        </template>
                    </el-calendar>
                    <el-calendar v-model="nextMonthDate" @update:model-value="onDateChange('next')">
                        <template #header="{ date }">{{ date }}</template>
                        <template #date-cell="{ data }">
                            <div :class="{ 'is-selected': eventsList.some(e => e.date === data.day) }">{{ moment(data.date).format('DD') }}</div>
                        </template>
                    </el-calendar>
                </div>
            </div>
        </Teleport>

        <div class="head-btn-list">
            <div class="view-selector">
                <el-dropdown trigger="click">
                    <el-button color="#435764" class="calendar-view">
                        {{ calendarView }}
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="calendarView = '月'">月</el-dropdown-item>
                            <el-dropdown-item @click="calendarView = '天'">天</el-dropdown-item>
                            <el-dropdown-item @click="calendarView = '未来事件'">未来事件</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-select v-model="course" placeholder="Select" class="course-sel">
                    <el-option label="所有课程" value="1" />
                    <el-option v-for="course in coursesList" :key="course.value" :label="course.label" :value="course.value" />
                </el-select>
            </div>
            <el-button color="#435764" @click="openAddEventDialog(new Date())">新事件</el-button>
        </div>
        <el-calendar v-model="mainCalendar" ref="mainCalendarRefs" v-if="calendarView === '月'">
            <template #header="{ date }">
                <el-button @click="prevMonth" link>
                    <el-icon size="16" color="#4c4c4c"><CaretLeft /></el-icon>
                    上个月
                </el-button>
                {{ date }}
                <el-button @click="nextMonth" link>
                    下个月
                    <el-icon size="16" color="#4c4c4c"><CaretRight /></el-icon>
                </el-button>
            </template>

            <template #date-cell="{ data }">
                <div class="day-box" @click="openAddEventDialog(mainCalendar)">{{ moment(data.date).format('DD') }}</div>
                <ul>
                    <li v-for="event in eventsList.filter(e => e.date === data.day)" @click="handleDateClick(event)">
                        <el-icon v-if="event.type == 1" size="12" color="#000"><DataAnalysis /></el-icon>
                        <el-icon v-if="event.type == 2" size="12" color="#000"><Tickets /></el-icon>
                        <el-tooltip effect="dark" :content="event.title" placement="right">
                            <span>{{ event.title }}</span>
                        </el-tooltip>
                    </li>
                </ul>
            </template>
        </el-calendar>

        <div class="day-wrapper" v-if="calendarView === '天'">
            <div class="day-wrapper-header">
                <el-button @click="prevDay" link>
                    <el-icon size="16" color="#4c4c4c"><CaretLeft /></el-icon>
                    {{ prevWeekday }}
                </el-button>
                {{ mainDay }}
                <el-button @click="nextDay" link>
                    {{ nextWeekday }}
                    <el-icon size="16" color="#4c4c4c"><CaretRight /></el-icon>
                </el-button>
            </div>
            <div class="rich-box" v-if="selectedEvent" v-html="selectedEvent.content"></div>
            <el-empty description="這一天沒有任何事件" image=" " v-else />
        </div>

        <div class="btn-list">
            <el-button @click="exportCalendarHandle" color="#F06423">导出行事历</el-button>
            <el-button @click="manageSubHandle" color="#F06423">管理订阅</el-button>
        </div>

        <el-dialog v-model="eventDialog" width="1240" title="新事件" class="mobile-dialog">
            <el-form :model="eventForm" label-width="25%" label-position="left">
                <el-form-item label="事件標題" required>
                    <el-input v-model="eventForm.name" />
                </el-form-item>
                <el-form-item label="日期">
                    <el-date-picker v-model="eventForm.date" type="datetime" format="YYYY/MM/DD HH:mm" />
                </el-form-item>
                <el-form-item label="事件類型"> 用户 </el-form-item>
                <el-button color="#55A630" @click="eventFormMoreTag = true">顯示更多選項...</el-button>
                <el-form-item> </el-form-item>
                <template v-if="eventFormMoreTag">
                    <el-form-item label="說明">
                        <el-input v-model="eventForm.description" :rows="3" type="textarea" />
                    </el-form-item>
                    <el-form-item label="位置">
                        <el-input v-model="eventForm.location" />
                    </el-form-item>
                    <el-form-item label="持續時間">
                        <el-radio-group v-model="eventForm.duration">
                            <el-radio value="0">不持續</el-radio>
                            <el-radio value="1">持續直到</el-radio>
                            <el-date-picker :disabled="eventForm.duration != '1'" v-model="eventForm.endDate" type="datetime" format="YYYY/MM/DD HH:mm" />
                            <el-radio value="2">持續多少分鐘</el-radio>
                            <el-input :disabled="eventForm.duration != '2'" v-model="eventForm.timedurationminutes" type="number" />
                        </el-radio-group>
                        <el-checkbox label="重覆此事件" value="1" v-model="eventForm.repeat" />
                    </el-form-item>
                    <el-form-item label="每週重覆，一起建立">
                        <el-input :disabled="eventForm.repeat != '1'" v-model="eventForm.repeats" type="number" />
                    </el-form-item>
                </template>
                <div class="btn-list">
                    <el-button @click="eventSubmitHandle" color="#F06423">儲存</el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'

import type { CalendarInstance } from 'element-plus'

import moment from 'moment'
import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

interface EventItem {
    id: number
    date: string | Date
    title: string
    status: number
    type: number
    content: string
}

interface eventKeyItem {
    isShow: boolean
    icon: string
    text: string
    color: string
}

const targetExists = ref(false)
const { locale } = useI18n<{ message: MessageSchema }, SupportedLocales>()
moment.locale(locale.value)

const eventKey = ref<eventKeyItem[]>([
    {
        isShow: true,
        icon: 'Files',
        text: '全網站',
        color: '#30638E',
    },
    {
        isShow: true,
        icon: 'TakeawayBox',
        text: '類目',
        color: '#20A39E',
    },
    {
        isShow: true,
        icon: 'DataAnalysis',
        text: '課程',
        color: '#FF5A5F',
    },
    {
        isShow: true,
        icon: 'User',
        text: '群組',
        color: '#3FA7D6',
    },
    {
        isShow: true,
        icon: 'Postcard',
        text: '用戶',
        color: '#FFBA49',
    },
    {
        isShow: true,
        icon: 'Calendar',
        text: '其他',
        color: '#CED4DA',
    },
])
const eventKeyHandle = (eventK: eventKeyItem) => {
    eventK.isShow = !eventK.isShow
}
const eventsList = ref<EventItem[]>([
    {
        id: 1,
        date: '2025-04-30',
        title: '提交反思報告 Submission of Reflective Essay',
        status: 1, // 1 表示已过期, 0 表示未过期
        type: 1, // 1 表示反思报告类型, 2表示考试类型, 其他待定
        content: '<div>这是一段富文本详细信息</div>提交反思報告 Submission of Reflective Essay',
    },
    {
        id: 2,
        date: '2025-04-30',
        title: '提交反思報告1 Submission of Reflective Essay1',
        status: 0, // 1 表示已过期, 0 表示未过期
        type: 2, // 1 表示反思报告类型, 2表示考试类型, 其他待定
        content: '<div>这是一段富文本详细信息</div>提交反思報告1 Submission of Reflective Essay1',
    },
    {
        id: 3,
        date: '2025-05-01',
        title: '提交反思報告 Submission of Reflective Essay2',
        status: 0, // 1 表示已过期, 0 表示未过期
        type: 2, // 1 表示反思报告类型, 2表示考试类型, 其他待定
        content: '<div>这是一段富文本详细信息</div>提交反思報告 Submission of Reflective Essay2',
    },
    {
        id: 4,
        date: '2025-04-30',
        title: '提交反思報告1 Submission of Reflective Essay4',
        status: 0, // 1 表示已过期, 0 表示未过期
        type: 2, // 1 表示反思报告类型, 2表示考试类型, 其他待定
        content: '<div>这是一段富文本详细信息</div>提交反思報告1 Submission of Reflective Essay4',
    },
    {
        id: 5,
        date: '2025-04-30',
        title: '提交反思報告1 Submission of Reflective Essay5',
        status: 0, // 1 表示已过期, 0 表示未过期
        type: 2, // 1 表示反思报告类型, 2表示考试类型, 其他待定
        content: '<div>这是一段富文本详细信息</div>提交反思報告1 Submission of Reflective Essay5',
    },
])
const selectedEvent = ref<EventItem | undefined>()
const handleDateClick = (event: EventItem) => {
    selectedEvent.value = event
    calendarView.value = '天'
}

// 格式化日期显示为"年月"格式
function formatDate(date: Date, formatStr: string): string {
    return moment(date).format(formatStr)
}
// 获取相邻月份的日期
function getAdjacentMonth(date: Date, offset: number): Date {
    return moment(date).add(offset, 'months').toDate()
}
// 根据不同的日历类型获取选中的日期
function getSelectedDate(calendarType: 'prev' | 'current' | 'next'): Date {
    if (calendarType === 'prev') {
        return prevMonthDate.value
    } else if (calendarType === 'current') {
        return currentMonthDate.value
    } else if (calendarType === 'next') {
        return nextMonthDate.value
    }
    return currentMonthDate.value
}

// 日历
// 当前月份的状态
const currentMonthDate = ref<Date>(new Date())
// 计算上个月的日期（基于当前月份计算）
const prevMonthDate = ref<Date>(getAdjacentMonth(currentMonthDate.value, -1))
// 计算下个月的日期（基于当前月份计算）
const nextMonthDate = ref<Date>(getAdjacentMonth(currentMonthDate.value, 1))
// 使用 computed 来计算相邻月份的日期
const prevMonthComputed = computed(() => {
    let date = getAdjacentMonth(currentMonthDate.value, -1)
    prevMonthDate.value = date
    return date
})
const nextMonthComputed = computed(() => {
    let date = getAdjacentMonth(currentMonthDate.value, 1)
    nextMonthDate.value = date
    return date
})
const onDateChange = (calendarType: 'prev' | 'current' | 'next') => {
    const selectedDate = getSelectedDate(calendarType)
    mainCalendar.value = new Date(selectedDate)
    mainDayDate.value = new Date(selectedDate)
}

// 右侧 下拉框
const calendarView = ref('月')
const course = ref('1')
const coursesList = ref([{ label: '2425-BC-DY-1', value: '300' }])

// 月
const mainCalendarRefs = ref<CalendarInstance>()
const mainCalendar = ref<Date>(new Date())
const prevMonth = () => {
    currentMonthDate.value = moment(mainCalendar.value).subtract(1, 'months').toDate()
    if (mainCalendarRefs.value) mainCalendarRefs.value.selectDate('prev-month')
    mainDayDate.value = mainCalendar.value
}
const nextMonth = () => {
    currentMonthDate.value = moment(mainCalendar.value).add(1, 'months').toDate()
    if (mainCalendarRefs.value) mainCalendarRefs.value.selectDate('next-month')
    mainDayDate.value = mainCalendar.value
}

// 天
const mainDayDate = ref(new Date()) // 存储 Date 对象
const mainDay = computed(() => formatDate(mainDayDate.value, locale.value === 'en' ? 'dddd, DD MM YYYY' : 'YYYY年MM月DD日 dddd'))
const currentMoment = computed(() => moment(mainDayDate.value))
const prevWeekday = computed(() => currentMoment.value.clone().subtract(1, 'day').format('dddd'))
const nextWeekday = computed(() => currentMoment.value.clone().add(1, 'day').format('dddd'))
const prevDay = () => {
    const prevDate = new Date(mainDayDate.value)
    prevDate.setDate(prevDate.getDate() - 1)

    // 检查是否跨月
    if (prevDate.getMonth() !== mainDayDate.value.getMonth()) {
        mainCalendar.value = prevDate
        mainDayDate.value = mainCalendar.value
    }

    mainDayDate.value = prevDate
    selectedEvent.value = eventsList.value.find(item => item.date === moment(prevDate).format('yyyy-MM-DD'))
}
const nextDay = () => {
    const nextDate = new Date(mainDayDate.value)
    nextDate.setDate(nextDate.getDate() + 1)

    // 检查是否跨月
    if (nextDate.getMonth() !== mainDayDate.value.getMonth()) {
        mainCalendar.value = nextDate
        mainDayDate.value = mainCalendar.value
    }

    mainDayDate.value = nextDate
    selectedEvent.value = eventsList.value.find(item => item.date === moment(nextDate).format('yyyy-MM-DD'))
}

// 导出 + 订阅
const exportCalendarHandle = () => {}
const manageSubHandle = () => {}

// 新事件
const eventDialog = ref(false)
const eventFormMoreTag = ref(false)
const openAddEventDialog = (date: Date) => {
    eventForm.value.date = date
    eventDialog.value = true
}
const eventForm = ref({
    name: '',
    date: mainCalendar,
    description: '',
    location: '',
    duration: '0',
    endDate: moment().add(1, 'month'),
    timedurationminutes: '',
    repeat: '0',
    repeats: 1,
})
const eventSubmitHandle = () => {}

// 监听语种
watch(locale, () => {
    moment.locale(locale.value)
    mainDayDate.value = new Date(mainDayDate.value)
})

onMounted(() => {
    targetExists.value = !!document.querySelector('#before-navigation')
})
</script>

<style lang="less" scoped>
.card-box {
    margin-bottom: 38px;

    &:last-child {
        margin-bottom: 0;
    }
}

.event-keywords-card {
    .event-item {
        margin-bottom: 6px;
        display: flex;
        align-items: center;
        gap: 4px;

        &:last-child {
            margin-bottom: 0;
        }

        .show-btn {
            padding: 1px 4px;
            line-height: 1;
        }

        .icon {
            line-height: 1;
        }

        .event-text {
            font-size: 15px;
            color: #4c4c4c;
        }
    }
}

.calendar-list-card {
    .computed-hide {
        position: absolute;
        z-index: -1;
    }
}

:deep(.el-calendar) {
    --el-calendar-header-border-bottom: none;
    --el-calendar-border: none;
    --el-calendar-cell-width: 24px;
    --el-calendar-selected-bg-color: transparent;

    margin-bottom: 15px;
    background-color: transparent;

    &:last-child {
        margin-bottom: 0;
    }

    .el-calendar__header {
        margin-bottom: 5px;
        border-radius: 2px;
        padding: 0;
        line-height: 24px;
        justify-content: center;
        background-color: #f06423;
        color: #fff;
        font-size: 12px;
    }

    .el-calendar__body {
        padding: 0;

        .el-calendar-table {
            tr {
                th {
                    border-right: 1px solid #fff;
                    padding: 0;
                    font-size: 12px;
                    color: #000;
                    line-height: 24px;
                    background-color: #ececec;

                    &:last-child {
                        border: none;
                    }
                }

                td {
                    line-height: 24px;

                    &.is-today {
                        background-color: #ababab;
                        color: #fff;
                    }

                    .is-selected {
                        background-color: #f06423;
                        height: 100%;
                        color: #fff;
                    }

                    &.prev,
                    &.next {
                        opacity: 0;
                        position: relative;
                        z-index: -1;
                    }
                }

                .el-calendar-day {
                    padding: 0 0.5px;
                    text-align: center;
                    font-size: 12px;
                    vertical-align: middle;

                    span {
                        vertical-align: middle;
                    }
                }
            }
        }
    }
}

.el-form {
    padding: 0 23px;

    .el-radio-group {
        .el-radio {
            display: block;
            width: 100%;
        }
    }

    .btn-list {
        border-top: 1px solid #dee2e6;
        padding-top: 15px;
        display: flex;
        justify-content: center;
    }
}
</style>
